#include "core/PropertyObfuscator.h"
#include "core/WhitelistManager.h"
#include "utils/RandomGenerator.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

PropertyObfuscator::PropertyObfuscator()
    : m_objcPropertyRegex("@property\\s*(?:\\([^)]*\\))?\\s*(?:\\w+\\s*\\*?\\s+)?(\\w+)")
    , m_swiftPropertyRegex("(?:var|let)\\s+(\\w+)\\s*:")
{
}

PropertyObfuscator::~PropertyObfuscator() = default;

QMap<QString, QString> PropertyObfuscator::generateMappings(const QStringList &files, WhitelistManager *whitelist)
{
    QMap<QString, QString> mappings;
    QStringList allPropertyNames;
    
    // 1. 收集所有属性名
    for (const QString &filePath : files) {
        QStringList propertyNames = extractPropertyNames(filePath);
        allPropertyNames.append(propertyNames);
    }
    
    // 2. 去重
    allPropertyNames.removeDuplicates();
    
    // 3. 生成映射
    for (const QString &propertyName : allPropertyNames) {
        if (shouldObfuscate(propertyName, whitelist)) {
            QString obfuscatedName = generateObfuscatedName(propertyName);
            
            // 确保没有冲突
            while (mappings.values().contains(obfuscatedName) || 
                   allPropertyNames.contains(obfuscatedName)) {
                obfuscatedName = generateObfuscatedName(propertyName);
            }
            
            mappings[propertyName] = obfuscatedName;
            qDebug() << "Property Mapping:" << propertyName << "->" << obfuscatedName;
        }
    }
    
    return mappings;
}

QStringList PropertyObfuscator::extractPropertyNames(const QString &filePath)
{
    QStringList propertyNames;
    
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return propertyNames;
    }
    
    QTextStream in(&file);
    QString content = in.readAll();
    file.close();
    
    // 检测文件类型
    bool isSwift = filePath.endsWith(".swift");
    
    if (isSwift) {
        // Swift属性提取
        QRegularExpressionMatchIterator it = m_swiftPropertyRegex.globalMatch(content);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            propertyNames.append(match.captured(1));
        }
    } else {
        // Objective-C属性提取
        QRegularExpressionMatchIterator it = m_objcPropertyRegex.globalMatch(content);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            propertyNames.append(match.captured(1));
        }
    }
    
    return propertyNames;
}

QString PropertyObfuscator::generateObfuscatedName(const QString &originalName)
{
    RandomGenerator generator;
    
    QString prefix = m_prefix.isEmpty() ? generator.generateString(2, false, true) : m_prefix;
    QString suffix = m_suffix.isEmpty() ? generator.generateString(4, true, true) : m_suffix;
    
    // 生成驼峰命名风格的属性名
    QString middle = generator.generateString(4, true, false);
    middle[0] = middle[0].toUpper();
    
    return prefix + middle + suffix;
}

bool PropertyObfuscator::shouldObfuscate(const QString &propertyName, WhitelistManager *whitelist)
{
    // 检查白名单
    if (whitelist && whitelist->isWhitelisted(propertyName)) {
        return false;
    }
    
    // 检查常见的系统属性名
    QStringList systemProperties = {
        "frame", "bounds", "center", "transform", "alpha",
        "backgroundColor", "tintColor", "text", "font", "textColor",
        "delegate", "dataSource", "tag", "hidden", "enabled",
        "selected", "highlighted", "contentMode", "clipsToBounds"
    };
    
    if (systemProperties.contains(propertyName)) {
        return false;
    }
    
    // 检查属性名长度
    if (propertyName.length() < 3) {
        return false;
    }
    
    // 检查是否是IBOutlet或IBAction
    if (propertyName.startsWith("ib") || propertyName.startsWith("IB")) {
        return false;
    }
    
    return true;
}